import 'package:flutter/material.dart';
import 'package:shining_red_star/api/list_number.dart';
import 'package:shining_red_star/definitions/router.dart';
import 'package:shining_red_star/model/number.dart';
import 'package:shining_red_star/widgets/number_index_card.dart';
import '../../model/router_params.dart';
import '../../widgets/auto_grid.dart';
import '../../wrappers/safe-area.dart';

class NumberIndexPage extends StatefulWidget {
  const NumberIndexPage({super.key});

  @override
  State<NumberIndexPage> createState() => _NumberIndexPageState();
}

class _NumberIndexPageState extends State<NumberIndexPage> {
  List<NumberInfo> numberList = [];

  void loadData() {
    listNumber().then((res) {
      setState(() {
        numberList = res;
      });
    });
  }

  void nav({String? id}) {
    Navigator.pushNamed(context, RouterKey.numberDetail.value,
        arguments: CommonDetailRouterArguments(
          id: id,
        ));
  }

  @override
  void initState() {
    super.initState();
    loadData();
  }

  @override
  Widget build(BuildContext context) {
    int i = 0;
    return SafeAreaPageWrapper(
      padding: EdgeInsets.all(12),
      child: numberList.isEmpty
          ? Center(
              child: Text('数据加载中'),
            )
          : AutoGrid(
              expectItemWidth: 128,
              expectItemHeight: 96,
              mainAxisSpacing: 12,
              crossAxisSpacing: 12,
              keepProportion: true,
              children: numberList.map((item) {
                return NumberIndexCard(
                  autofocus: i++ == 0,
                  number: item,
                  onConfirm: () {
                    nav(id: item.value.toString());
                  },
                );
              }).toList(),
            ),
    );
  }
}
